package com.etc.test

import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.streaming.{Milliseconds, StreamingContext}

/**
 * @Author kalista
 * @Description
 * @Date 2021/5/23  10:53
 * */
object WordCountkafka {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setAppName("SteamingWordCount").setMaster("local[3]")
    val sc = new SparkContext(conf)
    //StreamingContext是对SparkContext的包装，包了一层就增加了实时的功能
    //第二个参数是小批次产生的时间间隔
    val ssc = new StreamingContext(sc, Milliseconds(5000))
    ssc.checkpoint("e:\\spark\\checkpint\\springstreaming_kafka")


    // 构建kafka连接得map
    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> "hdp-01:9092,hdp-02:9092,hdp-03:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "test0002",
      "auto.offset.reset" -> "latest",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )


    // topic
    val topics = Array("hai_kou_gps_topic")


    val value: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )

    val wordAndOne = value.map(x=>x.value()).flatMap(x=>x.split(",")).map((_,1))


    //聚合
    val reduced: DStream[(String, Int)] = wordAndOne.updateStateByKey((vals:Seq[Int],sumOpt:Option[Int])=>{
      var count = vals.sum
      if (!sumOpt.isEmpty){
        count = count + sumOpt.get
      }
      Some(count)
    })
    reduced.print()



    ssc.start()
    ssc.awaitTermination()
    ssc.stop()










  }

}
